<?php

class m120201_073446_material_expense extends CDbMigration {
	public function safeUp() {
		$this
			->createTable('erp_material_expense',
				array(
					'id' => 'pk',
					'expenseDate' => 'date',
					'receiptCount' => 'int',
					'totalPrice' => 'decimal(16,2)',
					'note' => 'string',
					'createTime' => 'datetime',
					'createUserId' => 'int',
					'updateTime' => 'datetime',
					'updateUserId' => 'int',
				));
		$this
			->createIndex("material_expense_create_user_id", 'erp_material_expense', 'createUserId');
		$this
			->addForeignKey('fk_material_expense_create_user_id', 'erp_material_expense',
				'createUserId', 'erp_user', 'id', 'SET NULL', 'CASCADE');
		$this
			->createIndex("material_expense_update_user_id", 'erp_material_expense', 'updateUserId');
		$this
			->addForeignKey('fk_material_expense_update_user_id', 'erp_material_expense',
				'updateUserId', 'erp_user', 'id', 'SET NULL', 'CASCADE');

		$this->addColumn('erp_material_receipt', 'materialExpenseId', 'int');
		$this
			->createIndex("material_receipt_expense_id", 'erp_material_receipt',
				'materialExpenseId');
		$this
			->addForeignKey('fk_material_receipt_expense_id', 'erp_material_receipt',
				'materialExpenseId', 'erp_material_expense', 'id', 'SET NULL', 'CASCADE');

		$this->addColumn('erp_user_access', 'materialExpense', 'boolean');
		$this
			->insert('erp_auth_item',
				array(
					'name' => 'materialExpense',
					'type' => CAuthItem::TYPE_ROLE,
					'bizrule' => 'return AccessControl::check("materialExpense");',
				));
		$this
			->insert('erp_auth_item_child',
				array(
					'parent' => 'employee',
					'child' => 'materialExpense',
				));
	}

	public function safeDown() {

		$this->dropForeignKey('fk_material_receipt_expense_id', 'erp_material_receipt');
		$this->dropIndex("material_receipt_expense_id", 'erp_material_receipt');
		$this->dropColumn('erp_material_receipt', 'materialExpenseId');
		$this->dropTable('erp_material_expense');

		$this
			->delete('erp_auth_item_child',
				array(
					'and',
					'parent=:parent',
					'child=:child',
				),
				array(
					':parent' => 'employee',
					':child' => 'materialExpense',
				));
		$this
			->delete('erp_auth_item', 'name=:name', array(
				':name' => 'materialExpense',
			));
		$this->dropColumn('erp_user_access', 'materialExpense');
	}
}
